﻿using System;
using System.Data;
using NHibernate;

namespace HinduShop.DbClassLib
{
    public class UnitOfWorkImplementor : IUnitOfWork
    {
        private readonly ISession session;

        public UnitOfWorkImplementor(ISession sessionParam)
        {
            session = sessionParam;
        }

        public override void Dispose()
        {
            session.Dispose();
        }

        public IGenericTransaction BeginTransaction()
        {
            return new GenericTransaction(session.BeginTransaction());
        }

        public IGenericTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            return new GenericTransaction(session.BeginTransaction(isolationLevel));
        }

        public override void TransactionalFlush()
        {
            TransactionalFlush(IsolationLevel.ReadCommitted);
        }

        public void TransactionalFlush(IsolationLevel isolationLevel)
        {
            IGenericTransaction tx = BeginTransaction(isolationLevel);
            try
            {
                tx.Commit();
            }
            catch (Exception)
            {
                tx.Rollback();
                throw;
            }
            finally
            {
                tx.Dispose();
            }
        }

        public bool IsInActiveTransaction
        {
            get { return session.Transaction.IsActive; }
        }

        public ISession Session
        {
            get { return session; }
        }

        public void Flush()
        {
            session.Flush();
        }
    }
}